<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_form_checkers_checkMimeType extends f_form_Checker
{
	public function check()
	{
        $value = $this->getValue();

		if(is_array($value) && !empty($value["type"]) && in_array($value["type"], $this->getMimeType()))
		{
			return true;
		}
		else
		{
                    //if we have a file, so the mimetype isn't allowed
                    if(is_array($value) && !empty($value["tmp_name"]))
                    {
                        return $this->getErrorMessage();
                    }
                    else
                    {
                        //no file uploaded and this check doesn't have to check wether a file is uploaded or not
                        return true;
                    }
		}
	}

    private function getMimeType()
    {
        $mimes = split(",", $this->getAttribute("mimes"));
        $mimesType = array();
        
		$mimeFile = f_file_Resolver::resolvePath(FRAMEWORK_HOME, "file", "mimetype", "mimes.xml");

		$xmlcontent = f_xml_Xpath::getInstance($mimeFile)->fromXpath("extension")->getElements();

		/* @var $mime f_xml_XmlElement */
		foreach ($xmlcontent as $mime)
		{
			if(in_array($mime->getAttributeValue("id"), $mimes))
			{
				$tabs = $mime->getSubElements("mimetype");
                foreach($tabs as $tab)
                {
                    $mimesType[] = $tab;
                }
			}
		}

        return $mimesType;
    }
}